﻿using System;
using System.ComponentModel;
using System.Net;
using System.Text;
using Newtonsoft.Json;

namespace BabyCloudDrives.DesktopApp.Utilities
{
    public static class RESTUtility
    {
        public static T GetData<T>(Uri getUri)
        {
            T result = default(T);
            if (getUri == null) return result;
            WebClient webClient = new WebClient {Encoding = Encoding.UTF8};
            string responseJsonStr = webClient.DownloadString(getUri);
            result = JsonConvert.DeserializeObject<T>(responseJsonStr);
            return result;
        }

        public static void DownloadFile(Uri downloadUri, string savePath,
                                        Action<object, DownloadProgressChangedEventArgs> downloadProgressChanged = null,
                                        Action<object, AsyncCompletedEventArgs> downloadCompleted = null)
        {
            WebClient webClient = new WebClient {Encoding = Encoding.UTF8};
            if (downloadProgressChanged != null)
                webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloadProgressChanged);
            if (downloadCompleted != null)
                webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(downloadCompleted);
            if (downloadCompleted == null)
                webClient.DownloadFile(downloadUri, savePath);
            else
                webClient.DownloadFileAsync(downloadUri, savePath);
        }
    }
}